@echo off
setlocal EnableDelayedExpansion

:: Change to the directory where the batch file is located to execute Git commands
cd /d "%~dp0"

:: Check if inside a Git repository
git rev-parse --is-inside-work-tree >nul 2>&1
if %errorlevel% neq 0 (
    echo ERROR: Current directory is not a Git repository
    exit /b 1
)

:: Get Git information and handle possible errors
for /f "tokens=*" %%a in ('git rev-parse --short HEAD 2^>nul') do set GIT_SHA=%%a
for /f "tokens=*" %%a in ('git log -1 --format^="%%cd" --date^=short 2^>nul') do set GIT_DATE=%%a
for /f "tokens=*" %%a in ('git log -1 --format^="%%an" 2^>nul') do set GIT_AUTHOR=%%a

:: Remove possible quotes
set GIT_DATE=%GIT_DATE:"=%
set GIT_AUTHOR=%GIT_AUTHOR:"=%

:: Check if information was successfully obtained
if "%GIT_SHA%"=="" (
    echo ERROR: Unable to get Git version information
    set GIT_SHA=unknown
    set GIT_DATE=unknown
    set GIT_AUTHOR=unknown
)

:: Create temporary file to store new content
echo #define GIT_VERSION "%GIT_SHA%" > temp_GitVersion.h
echo #define GIT_DATE "%GIT_DATE%" >> temp_GitVersion.h

:: Check if version file exists and compare contents
if exist GitVersion.h (
    :: Extract SHA value from file
    for /f "tokens=3 delims== " %%a in ('findstr /C:"GIT_VERSION" GitVersion.h') do (
        set FILE_SHA=%%a
        set FILE_SHA=!FILE_SHA:"=!
    )
    
    :: Directly compare SHA values
    if not "!FILE_SHA!"=="%GIT_SHA%" (
        goto UPDATE_FILE
    )
    
    :: Perform text comparison
    fc /L GitVersion.h temp_GitVersion.h >nul 2>&1
    if %errorlevel% equ 0 (
        echo Version unchanged, keeping existing file
        echo Current version: %GIT_SHA%
        del temp_GitVersion.h
        exit /b 0
    )
)

:UPDATE_FILE
:: Copy temporary file to official file
copy /y temp_GitVersion.h GitVersion.h >nul
del temp_GitVersion.h

:: Output information for compilation log display
echo Git SHA: %GIT_SHA%
echo Git Commit Date: %GIT_DATE%
echo Git Author: %GIT_AUTHOR%
exit /b 0

::===========================================================================
:: 脚本名称: GetGitSHA.bat
:: 脚本版本: v1.0.1
:: 更新日期: 2025-06-25
:: 脚本用途: 自动从Git仓库提取版本信息并生成头文件
:: 适用范围: 嵌入式开发(Keil等IDE)项目版本管理
:: 脚本功能:
::   1. 从Git仓库获取当前提交SHA、日期和作者信息
::   2. 生成GitVersion.h头文件供C/C++项目使用
::   3. 智能比较新旧版本，仅在版本变更时更新文件
::   4. 避免不必要的文件修改，减少编译触发
::
:: 使用说明:
::   1. 将此脚本放在Git仓库根目录或项目目录中
::   2. 在IDE编译前步骤中调用此脚本
::   3. 在代码中包含"GitVersion.h"即可使用版本信息
::
:: 依赖工具:
::   - Git命令行工具 (需已安装并添加到PATH)
::
:: 输出文件:
::   - GitVersion.h: 包含以下宏定义
::     #define GIT_VERSION "提交哈希值"
::     #define GIT_DATE "提交日期"
::===========================================================================
